import MySQLdb
import requests
import re

class Tools:
    def __init__(self):
        pass

    def string_to_dict(self, string):
        dict = {}
        for i in string.split('\n'):
            i = i.replace(' ', '')
            i = i.split(':', maxsplit=1)
            dict[i[0]] = i[1].strip()
        return dict


    def imp(self):
        return print('from lxml import etree\nimport requests\nfrom fake_useragent import UserAgent\nimport time')

    def set_sqlconnect(self, db, charset='utf8'):
        conn = MySQLdb.connect(
            user = 'root',
            password = '123456',
            db = db,
            host = 'localhost',
            port = 3306,
            charset = charset
        )
        cursor = conn.cursor()
        return [conn, cursor]

    def list_to_string(self, list):
        '''
        将列表循环，拼接出一个长字符串
        :return:
        '''
        string = ''
        for i in list:
            i = i.strip()
            i = i.replace(' ', '')
            string += i
        return string

    def xpath(self, str):
        '''
        返回
        :param str:
        :return:
        '''

    def self_ip(self):
        url = 'http://txt.go.sohu.com/ip/soip'
        resp = requests.get(url).text
        result = re.findall(r'user_ip="(.*?)";sohu', resp)
        return result[0]